package com.xgkj.eatshow.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.WeiXinPayUtil;
import com.xgkj.diyiketang.R;

import java.io.UnsupportedEncodingException;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
	public static final String WEIXIN_SHARE_SUCCESS_ACTION = "weixin_share_success_action";
	public static final String WEIXIN_LOGIN_SUCCESS_ACTION = "weixin_login_success_action";
	private IWXAPI api;
	public static String WX_CODE = "";
	private String openId;
	private String userUrl;
	private String nick;
	private String logoUrl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		PalLog.e("微信回调", "on create");
		api = WXAPIFactory.createWXAPI(this, ProtocolConst.APP_ID, true);
		api.registerApp(ProtocolConst.APP_ID);

		api.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
			case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
				break;
			case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
				break;
			default:
				break;
		}
	}

	@Override
	public void onResp(BaseResp resp) {
		int result = 0;
		String openId = resp.openId;
		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			WX_CODE = ((SendAuth.Resp) resp).code;
			System.out.println("openId:" + openId + "code:" + WX_CODE);
		}



		switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK:
				result = R.string.errcode_success;

				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				result = R.string.errcode_cancel;
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				result = R.string.errcode_deny;
				break;
			default:
				result = R.string.errcode_unknown;
				break;
		}
		//Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
		finish();
		if(resp.errCode == BaseResp.ErrCode.ERR_OK){
			Intent intent = new Intent(WEIXIN_SHARE_SUCCESS_ACTION);
			intent.putExtra(ProtocolConst.WEIXIN_OPENID, openId);
			sendBroadcast(intent);
			loadWXUserInfo();
		}
	}


	private void loadWXUserInfo() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + ProtocolConst.APP_ID + "&secret=" + ProtocolConst.APPSECRET + "&code=" + WX_CODE + "&grant_type=authorization_code";
				String tokenResult = null;
				try {
					tokenResult = new String (WeiXinPayUtil.httpGet(accessTokenUrl),"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (null != tokenResult) {
					JSONObject tokenObj = JSON.parseObject(tokenResult);
					String accessToken = tokenObj.getString("access_token");
					openId = tokenObj.getString("openid");
					userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;

					String wxUserInfo = null;
					try {
						wxUserInfo = new String(WeiXinPayUtil.httpGet(userUrl),"utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					JSONObject userObj = JSON.parseObject(wxUserInfo);
					nick = userObj.getString("nickname");
					PalLog.e("微信昵称",userUrl);
					logoUrl= userObj.getString("headimgurl");
					PalLog.e("微信头像",logoUrl);
					handler.sendEmptyMessage(0);

				}
			}
		}).start();
	}
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Intent intent = new Intent(WEIXIN_LOGIN_SUCCESS_ACTION);
			intent.putExtra(ProtocolConst.WEIXIN_OPENID, openId);
			intent.putExtra("LOGOURL",logoUrl);
			intent.putExtra("NICK",nick);
			sendBroadcast(intent);

		}
	};

}